local skynet = require "skynet"
local manager = require 'skynet.manager'
local mongo = require "skynet.db.mongo"

local host, port, db_name, username, password = 'localhost', 27017, 'skynet'
local c
--用户ID分配
local userid = 0

local CMD = {}
function CMD.Register(username, password)
    local ok, err, ret
    local db = c[db_name]
    ret = db.user_auth:findOne({username = username})
    if ret then
        return false, 'FAILED'
    end

    userid = userid + 1
    ok, err, ret = db.user_auth:safe_insert({username = username, password = password, userid = userid})
    if ok and ret and ret.n == 1 then
        ok, err, ret = db.global:safe_update({key = 'userid'}, {key = 'userid', value = userid})
        return true
    else
        return false, 'FAILED'
    end
end

function CMD.Auth(username, password)
    local ok, err, ret
    local db = c[db_name]
    ret = db.user_auth:findOne({username = username})
    if ret == nil or ret.password ~= password then
        return false
    else
        return true, ret.userid
    end
end

skynet.start(function()
    local ok, err, ret
    c = mongo.client(
            {
                host = host, port = port,
                --username = username, password = password,
                authdb = db_name,
            }
    )
    local db = c[db_name]

    ret = db.global:findOne({key='userid'})
    if ret and ret.value then
        userid = ret.value
    else
        ok, err, ret = db.global:safe_insert({key='userid', value = userid})
        if not (ok and ret and ret.n == 1) then
            skynet.error(err)
            skynet.exit()
            return
        end
    end

    manager.register('loginManager')
    skynet.dispatch("lua", function(_, _, cmd,  ...)
        local args = {...}
        --xpcall(function()
            local f = assert(CMD[cmd])
            skynet.ret(skynet.pack(f(table.unpack(args))))
        --end, function(error)
        --    skynet.error(debug.traceback(error))
        --    skynet.ret(skynet.pack(false, 'FAILED'))
        --end)
    end)
end)
